package com.ccsu.eb.controller;

import com.ccsu.eb.model.EbUser;
import com.ccsu.eb.service.EbUserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 用一句话描述
 * @Auther: 新梦想*陈超
 * @Date: 2022/3/18 15:35
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Resource
    private EbUserService ebUserService;
    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping("to_login")
    public String toLogin(){
        return "login";//templates/login.html

    }

    /**
     * 登录
     * @param ebUser
     * @return
     */
    @RequestMapping("login")
    public String login(Model model, EbUser ebUser, String verycode, HttpServletRequest request){
        //清除错误信息
        model.addAttribute("error",null);
        System.out.println("登录的用户名和密码为："+ebUser.getEuUserName()+"\t"+ebUser.getEuPassword());
        //TODO 1.验证验证码
        if (!CaptchaUtil.ver(verycode, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            model.addAttribute("error","验证码错误");
            return "forward:to_login";
        }
        //TODO 2.调用Service验证用户和密码
        EbUser loginUser = ebUserService.login(ebUser.getEuUserName(), ebUser.getEuPassword());
        if(loginUser==null){
            model.addAttribute("error","用户或密码错误");
            return "forward:to_login";
        }
        //TODO  3.绑定数据到sesssion
        request.getSession().setAttribute("lgnUser", loginUser);
        //TODO 4,返回view----html
        return "redirect:/index/index";//重定向到网站首页
    }
    /**
     * 生成图形验证码
     * @param request
     * @param response
     * @throws Exception
     */

    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }
}
